package com.dff.jrfw;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;
import java.util.Stack;

public class ActivityManager implements Application.ActivityLifecycleCallbacks {

    public void exit() {
        for (Activity activity : activityStack) {
            activity.finish();
        }
    }

    public void clearStackIfNotTop() {
        for (Activity activity : activityStack) {
            if (activity != getTopActivity()) {
                activity.finish();
            }
        }
    }

    private static volatile ActivityManager instance;
    private final Stack<Activity> activityStack = new Stack<>();
    private WeakReference<Activity> currentShowActivityWeakReference = null;

    public Activity getTopActivity() {
        if (currentShowActivityWeakReference != null) {
            return currentShowActivityWeakReference.get();
        }
        return null;
    }

    private ActivityManager() {

    }

    public static ActivityManager getInstance() {
        if (instance == null) {
            synchronized (ActivityManager.class) {
                if (instance == null) {
                    instance = new ActivityManager();
                }
            }
        }
        return instance;
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        activityStack.push(activity);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        if (currentShowActivityWeakReference != null) {
            currentShowActivityWeakReference.clear();
        }
        currentShowActivityWeakReference = new WeakReference<>(activity);
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        activityStack.remove(activity);
    }

}
